<template>
  <div class="modal-overlay" v-if="visible">
     <div class="modal-content modal-main">
        <div class="modal-header">
          <h2 class="modal-title">文件选择</h2>
          <button class="close-btn" @click="closeModal">
            <svg class="h-5 w-5" viewBox="0 0 24 24" fill="none">
              <path d="M6 18L18 6M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
        </div>
        <div class="file-container">
          <div class="file-card left-card">
            <div class="card-body">
              <div class="card-content">
                <div class="channel-header">
                  <h2 class="channel-title">左发</h2>
                </div>

                <div class="channels-container">
                  <div class="channel-section">
                    <div class="section-header">
                      <h4 class="section-title">A通道</h4>
                      <div class="search-wrapper">
                        <input
                          type="text"
                          v-model="searchA"
                          placeholder="搜索文件..."
                          class="search-input"
                        />
                        <button
                          v-if="searchA"
                          @click="searchA = ''"
                          class="clear-btn"
                        >
                          <svg class="clear-icon" viewBox="0 0 24 24" fill="none">
                            <path d="M6 18L18 6M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                          </svg>
                        </button>
                      </div>
                    </div>
                      <table class="tech-table">
                        <thead>
                          <tr>
                            <th class="select-col">选择</th>
                            <th>文件名</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr v-for="file in filteredFilesA" :key="file.name">
                            <td>
                              <input
                                type="checkbox"
                                name="fileA"
                                class="tech-radio"
                                :checked="tempSelectedFileA === file.name"
                                @change="selectFileA(file.name)"
                              />
                            </td>
                            <td class="filename-cell" :title="file.name"><div class="filename-text">{{ file.name }}</div></td>
                          </tr>
                        </tbody>
                      </table>
                  </div>

                  <div class="channel-section">
                    <div class="section-header">
                      <h4 class="section-title">B通道</h4>
                      <div class="search-wrapper">
                        <input
                          type="text"
                          v-model="searchB"
                          placeholder="搜索文件..."
                          class="search-input"
                        />
                        <button
                          v-if="searchB"
                          @click="searchB = ''"
                          class="clear-btn"
                        >
                          <svg class="clear-icon" viewBox="0 0 24 24" fill="none">
                            <path d="M6 18L18 6M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                          </svg>
                        </button>
                      </div>
                    </div>
                      <table class="tech-table">
                        <thead>
                          <tr>
                            <th class="select-col">选择</th>
                            <th>文件名</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr v-for="file in filteredFilesB" :key="file.name">
                            <td>
                              <input
                                type="checkbox"
                                name="fileB"
                                class="tech-radio"
                                :checked="tempSelectedFileB === file.name"
                                @change="selectFileB(file.name)"
                              />
                            </td>
                            <td class="filename-cell" :title="file.name"><div class="filename-text">{{ file.name }}</div></td>
                          </tr>
                        </tbody>
                      </table>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="file-card right-card">
            <div class="card-body">
              <div class="card-content">
                <div class="channel-header">
                  <h2 class="channel-title">右发</h2>
                </div>

                <div class="channels-container">
                  <div class="channel-section">
                    <div class="section-header">
                      <h4 class="section-title">A通道</h4>
                      <div class="search-wrapper">
                        <input
                          type="text"
                          v-model="searchC"
                          placeholder="搜索文件..."
                          class="search-input"
                        />
                        <button
                          v-if="searchC"
                          @click="searchC = ''"
                          class="clear-btn"
                        >
                          <svg class="clear-icon" viewBox="0 0 24 24" fill="none">
                            <path d="M6 18L18 6M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                          </svg>
                        </button>
                      </div>
                    </div>
                      <table class="tech-table">
                        <thead>
                          <tr>
                            <th class="select-col">选择</th>
                            <th>文件名</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr v-for="file in filteredFilesC" :key="file.name">
                            <td>
                              <input
                                type="checkbox"
                                name="fileC"
                                class="tech-radio"
                                :checked="tempSelectedFileC === file.name"
                                @change="selectFileC(file.name)"
                              />
                            </td>
                            <td class="filename-cell" :title="file.name"><div class="filename-text">{{ file.name }}</div></td>
                          </tr>
                        </tbody>
                      </table>
                  </div>

                  <div class="channel-section">
                    <div class="section-header">
                      <h4 class="section-title">B通道</h4>
                      <div class="search-wrapper">
                        <input
                          type="text"
                          v-model="searchD"
                          placeholder="搜索文件..."
                          class="search-input"
                        />
                        <button
                          v-if="searchD"
                          @click="searchD = ''"
                          class="clear-btn"
                        >
                          <svg class="clear-icon" viewBox="0 0 24 24" fill="none">
                            <path d="M6 18L18 6M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                          </svg>
                        </button>
                      </div>
                    </div>
                      <table class="tech-table">
                        <thead>
                          <tr>
                            <th class="select-col">选择</th>
                            <th>文件名</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr v-for="file in filteredFilesD" :key="file.name">
                            <td>
                              <input
                                type="checkbox"
                                name="fileD"
                                class="tech-radio"
                                :checked="tempSelectedFileD === file.name"
                                @change="selectFileD(file.name)"
                              />
                            </td>
                            <td class="filename-cell" :title="file.name"><div class="filename-text">{{ file.name }}</div></td>
                          </tr>
                        </tbody>
                      </table>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="tech-btn import-btn-cancel" @click="closeModal">取消</button>
          <button class="tech-btn import-btn-primary" @click="returnDraw">确认</button>
        </div>
      </div>
  </div>
  <!-- 消息提示组件 -->
  <Message ref="messageRef" />
</template>

<script setup lang="ts">
import {onMounted, ref, computed, watch} from 'vue'
import WithAPI from './parameter.api.ts'
import { useFileSelectionStore } from '@/stores/fileSelection'
import Message from '@/components/BaseComponents/Message.vue'
const messageRef = ref<InstanceType<typeof Message> | null>(null)
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(['update:visible', 'confirm']);
const mode = localStorage.getItem('mode')
const importFileIndex = localStorage.getItem('importFileIndex')
// 左发
const filesA = ref<Array<{ name: string }>>([])
const filesB = ref<Array<{ name: string }>>([])

// 右发
const filesC = ref<Array<{ name: string }>>([])
const filesD = ref<Array<{ name: string }>>([])

const fileSelectionStore = useFileSelectionStore()

// 选中状态
const selectedFileA = ref(fileSelectionStore.selectedFileA)
const selectedFileB = ref(fileSelectionStore.selectedFileB)
const selectedFileC = ref(fileSelectionStore.selectedFileC)
const selectedFileD = ref(fileSelectionStore.selectedFileD)

// 临时选中状态
const tempSelectedFileA = ref(fileSelectionStore.selectedFileA)
const tempSelectedFileB = ref(fileSelectionStore.selectedFileB)
const tempSelectedFileC = ref(fileSelectionStore.selectedFileC)
const tempSelectedFileD = ref(fileSelectionStore.selectedFileD)

// 选择处理函数
const selectFileA = (name: string) => {
    if (tempSelectedFileA.value === name) {
        tempSelectedFileA.value = ''; // 如果点击已选中的文件，取消选择
    } else {
        tempSelectedFileA.value = name; // 否则选择新文件
    }
}

const selectFileB = (name: string) => {
    if (tempSelectedFileB.value === name) {
        tempSelectedFileB.value = ''; // 如果点击已选中的文件，取消选择
    } else {
        tempSelectedFileB.value = name; // 否则选择新文件
    }
}

const selectFileC = (name: string) => {
    if (tempSelectedFileC.value === name) {
        tempSelectedFileC.value = ''; // 如果点击已选中的文件，取消选择
    } else {
        tempSelectedFileC.value = name; // 否则选择新文件
    }
}

const selectFileD = (name: string) => {
    if (tempSelectedFileD.value === name) {
        tempSelectedFileD.value = ''; // 如果点击已选中的文件，取消选择
    } else {
        tempSelectedFileD.value = name; // 否则选择新文件
    }
}

function getFileWithCleaned() {
    WithAPI.getFileWithCleaned().then((res: { data: string[] }) => {
      if (res && res.data) {
        if (res.data.length == 0) {
          messageRef.value?.show({
            type: 'warning',
            content: '没有找到文件',
            duration: 3000
          });
        }
        let rules: Array<{ name: string }> = [];
        res.data.forEach((item: string) => {
          rules.push({
            name: item,
          })
        });
        filesA.value = rules;
        filesB.value = rules;
        filesC.value = rules;
        filesD.value = rules;
      }
    }).catch((error: any) => {
      messageRef.value?.show({
        type: 'warning',
        content: error.response.data.msg,
        duration: 3000
      });
    })
}

function returnDraw() {
  // 更新内存中的选中状态
  selectedFileA.value = tempSelectedFileA.value
  selectedFileB.value = tempSelectedFileB.value
  selectedFileC.value = tempSelectedFileC.value
  selectedFileD.value = tempSelectedFileD.value

  // 更新 store 中的选中状态
  fileSelectionStore.updateFileA(tempSelectedFileA.value)
  fileSelectionStore.updateFileB(tempSelectedFileB.value)
  fileSelectionStore.updateFileC(tempSelectedFileC.value)
  fileSelectionStore.updateFileD(tempSelectedFileD.value)

  let params = [
    {
      channelId: 'leftA',
      fileName: selectedFileA.value,
      parameters: {}
    },
    {
      channelId: 'leftB',
      fileName: selectedFileB.value,
      parameters: {}
    },
    {
      channelId: 'rightA',
      fileName: selectedFileC.value,
      parameters: {}
    },
    {
      channelId: 'rightB',
      fileName: selectedFileD.value,
      parameters: {}
    }
  ];

  let draw = JSON.stringify(params)
  emit('confirm', draw);
  closeModal();
}

function closeModal() {
  // 重置临时选中状态为内存中的选中状态
  tempSelectedFileA.value = selectedFileA.value
  tempSelectedFileB.value = selectedFileB.value
  tempSelectedFileC.value = selectedFileC.value
  tempSelectedFileD.value = selectedFileD.value
  emit('update:visible', false);
}

const searchA = ref('')
const searchB = ref('')
const searchC = ref('')
const searchD = ref('')

// 过滤后的文件列表
const filteredFilesA = computed(() => {
  return filesA.value.filter(file =>
    file.name.toLowerCase().includes(searchA.value.toLowerCase())
  )
})

const filteredFilesB = computed(() => {
  return filesB.value.filter(file =>
    file.name.toLowerCase().includes(searchB.value.toLowerCase())
  )
})

const filteredFilesC = computed(() => {
  return filesC.value.filter(file =>
    file.name.toLowerCase().includes(searchC.value.toLowerCase())
  )
})

const filteredFilesD = computed(() => {
  return filesD.value.filter(file =>
    file.name.toLowerCase().includes(searchD.value.toLowerCase())
  )
})
 
// 自动选择文件 如果传来多个文件名，按左发A、左发B、右发A、右发B顺序选择
function autoSelectFile(files: any[], firstEnter: boolean) {
  filesA.value = []
  filesB.value = []
  filesC.value = []
  filesD.value = []
  files.forEach((file, index) => {
    const fileName = typeof file === 'string' ? file : file.fileName || file.name || file
    filesA.value.push({ name: fileName })
    filesB.value.push({ name: fileName })
    filesC.value.push({ name: fileName })
    filesD.value.push({ name: fileName })
  })
  if (firstEnter) {
    if (files.length > 0) {
      if (files.length == 1) {
        tempSelectedFileA.value = files[0].fileName
      } else if (files.length == 2) {
        tempSelectedFileA.value = files[0].fileName
        tempSelectedFileB.value = files[1].fileName
      } else if (files.length == 3) {
        tempSelectedFileA.value = files[0].fileName
        tempSelectedFileB.value = files[1].fileName
        tempSelectedFileC.value = files[2].fileName
      } else if (files.length == 4) {
        tempSelectedFileA.value = files[0].fileName
        tempSelectedFileB.value = files[1].fileName
        tempSelectedFileC.value = files[2].fileName
        tempSelectedFileD.value = files[3].fileName
      } else {
        tempSelectedFileA.value = files[0].fileName
        tempSelectedFileB.value = files[1].fileName
        tempSelectedFileC.value = files[2].fileName
        tempSelectedFileD.value = files[3].fileName
      }
    }
    // 更新 store 中的选中状态
    fileSelectionStore.updateFileA(tempSelectedFileA.value)
    fileSelectionStore.updateFileB(tempSelectedFileB.value)
    fileSelectionStore.updateFileC(tempSelectedFileC.value)
    fileSelectionStore.updateFileD(tempSelectedFileD.value)
  }

}

const autoSelectSampleFile = (fileName: string) => {
  filesA.value = []
  filesB.value = []
  filesC.value = []
  filesD.value = []
  filesA.value.push({ name: fileName })
  filesB.value.push({ name: fileName })
  filesC.value.push({ name: fileName })
  filesD.value.push({ name: fileName })
  tempSelectedFileA.value = fileName
  
  returnDraw()
}
const parameterModelRef = ref<HTMLElement | null>(null)
onMounted(() => {
  if (!importFileIndex) {
    getFileWithCleaned();
  }
})

defineExpose({
  autoSelectFile,
  getFileWithCleaned,
  autoSelectSampleFile
})
</script>

<style scoped>

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
    background-color: rgba(0, 0, 0, 0.5);
  align-items: center;
  z-index: 1000;
  animation: fadeIn 0.2s ease-out;
  padding: 10px;
}

.modal-content {
  backdrop-filter: blur(10px);
  border-radius: 8px;
  padding: 1px;
  width: 100%;
  max-width: 1000px;
  max-height: calc(100vh - 5em);
  overflow-y: auto;
  z-index: 51;
  position: relative;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
}

.modal-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: var(--text-color)
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-color);
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
}
.close-btn:hover {
  color: var(--global-color-black);
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
}

.import-btn-cancel, .import-btn-primary {
  height: 36px;
  font-size: 0.875rem;
  padding: 0.35rem 0.75rem;
  border-radius: 0.375rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.import-btn-cancel {
  border: 1px solid var(--error-color) !important;
  color: var(--error-color) !important;
  &:hover{
    color: var(--text-color) !important;
    background-color: var(--error-color) !important;
  }
}

.import-btn-primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.import-btn-primary:disabled {
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    transform: translateY(-20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}


.file-container {
  display: flex;
  gap: 1px;
  flex: 1;
  min-height: 0;
  contain: layout;
  padding: 0;
  overflow-y: auto;
  height: 100%;
  //background: #f8fafc;
  position: relative;
}

.file-card {
  flex: 1;
  //background: #fff;
  border-radius: 0;
  box-shadow: none;
  overflow: hidden;
  position: relative;
  border: none;
  contain: layout;
  transform: translateZ(0);
  backface-visibility: hidden;
  display: flex;
  flex-direction: column;
  width: 100%;
}


.card-body {
  padding: 12px;
  height: 100%;
  contain: layout;
  overflow-y: auto;
  width: 100%;
}

.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  contain: layout;
  width: 100%;
}

.channel-header {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  contain: layout;
}

.channel-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
  text-shadow: none;
  will-change: transform;
  transform: translateZ(0);
}

.channels-container {
  display: flex;
  gap: 12px;
  padding: 0 12px;
  height: calc(100% - 20px);
}

.channel-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  height: 100%;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-color);
  margin-left: 0px;
  contain: layout;
}

.tech-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  table-layout: fixed;
  contain: strict;
  border: 1px solid var(--table-solid);
  border-radius: 6px;
  overflow: hidden;
}

.tech-table thead {
  display: block;
  background: var(--table-header-bg-color);
  border-bottom: 1px solid var(--table-solid);
}

.tech-table tbody {
  display: block;
  overflow-y: auto;
  height: 300px;
  padding-bottom: 1px;
  background: var(--table-body-bg-color);
}

.tech-table thead tr,
.tech-table tbody tr {
  display: table;
  width: 100%;
  table-layout: fixed;
  height: 20%;
  vertical-align: middle;
}

.tech-table th {
  font-weight: 500;
  color: var(--text-color);
  //background: #fff;
  //border-bottom: 1px solid rgba(30, 64, 175, 0.2);
  //box-shadow: 0 1px 0 rgba(30, 64, 175, 0.2);
}

.tech-table th,
.tech-table td {
  padding: 10px 8px;
  text-align: center;
  contain: layout;
  height: 41px;
  width: 30%;
  box-sizing: border-box;
}

.tech-table td {
  border-bottom: 1px solid var(--modal-divide);
  contain: layout;
  background: var(--table-body-bg-color);
  vertical-align: middle;
  padding: 8px;
  height: 41px;
  line-height: 41px;
}

.tech-table tbody tr:last-child td {
  border-bottom: 1px solid var(--table-solid);;
}

.tech-table th:last-child,
.tech-table td:last-child {
  width: 70%;
}

.filename-cell {
  text-align: left;
  padding: 7px;
  //margin-left: -10;
}

.filename-text {
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.select-col {
  width: 30%;
  min-width: 60px;
  contain: layout;
  text-align: center;
  vertical-align: middle;
  height: 41px;
  line-height: 41px;
}

.tech-radio {
    appearance: none;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    border: 1px solid var(--border-color-base);
    outline: none;
    cursor: pointer;
    position: relative;
    transition: border-color 0.2s ease, background-color 0.2s ease, box-shadow 0.2s ease;
    will-change: transform, border-color, background-color, box-shadow;
    transform: translateZ(0);
    backface-visibility: hidden;
    vertical-align: middle;
    margin: 2px;
}

.tech-radio:checked {
    background-color: var(--ant-checkbox-checked);
    border: 1px solid var(--btn-click-color);
    box-shadow: var(--ant-checkbox-shadow);
}

.tech-radio:checked::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) translateZ(0);
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: var(--global-color-white);
    display: block;
}

.search-wrapper {
  position: relative;
  width: 160px;
}

.search-input {
  width: 100%;
  padding: 6px 10px;
  padding-right: 32px;
  border: 1px solid var(--input-border-color);
  border-radius: 4px;
  font-size: 12px;
  color: var(--text-color);
  background: var(--input-background);
  transition: all 0.2s ease;
}

.search-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

.search-input::placeholder {
  color: var(--input-text-color);
}


.clear-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  padding: 4px;
  cursor: pointer;
  color: var(--text-color);
  transition: color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.clear-btn:hover {
  color: var(--global-color-black);
}

.clear-icon {
  width: 16px;
  height: 16px;
}

@media (max-width: 1024px) {
  .modal-content {
    max-width: 80vw;
    max-height: 80vh;
    width: 85vw;
    height: 78vh;
    font-size: 12px;
  }
  .modal-title,
  .channel-title {
    font-size: 14px;
  }
  .section-title {
    font-size: 10px;
  }
  .tech-table th,
  .tech-table td {
    font-size: 11px;
    padding: 2px 0px;
    text-align: center;
  }
  .import-btn-cancel,
  .import-btn-primary {
    font-size: 0.7rem;
    height: 26px;
    padding: 0.15rem 0.4rem;
  }
  .search-input {
    font-size: 11px;
    padding: 3px 0px;
  }
  .channel-title {
    font-size: 14px;
  }
  .search-wrapper {
    width: 134px;
  }
  .search-input {
    font-size: 10px;
    padding: 2px 6px;
  }
  .tech-table th {
    font-size: 10px;
    padding: 3px 2px;
  }
  .tech-radio {
    width: 12px;
    height: 12px;
  }
  .tech-radio:checked::after {
    width: 4px;
    height: 4px;
  }
  .tech-table th:last-child,
  .tech-table td:last-child {
    width: 70%;
  }
  .filename-cell {
    font-size: 10px;
    text-align: left;
    padding: 2px 4px;
    max-width: 0;
  }
  .filename-text {
    padding: 0 1px;
    font-size: 10px;
    line-height: 1.2;
  }
  .select-col {
    width: 30%;
    min-width: 40px;
    padding: 2px;
  }
  .tech-table tbody::-webkit-scrollbar {
    width: 4px;
  }
    .tech-table tbody::-webkit-scrollbar-track {
        background-color: var(--webkit-track-color);
        border-radius: 4px;
    }
    /* 滚动条滑块 */
    .tech-table tbody::-webkit-scrollbar-thumb {
        background-color: var(--webkit-thumb-color);
        border-radius: 4px;
    }
    /* 滚动条滑块 hover 状态 */
    .tech-table tbody::-webkit-scrollbar-thumb:hover {
        background-color: var(--webkit-thumb-hover-color);
    }

  .table-container {
    max-height: 500px;
    padding-bottom: 1px;
  }
  .tech-table tbody {
    height: 200px;
    overflow-y: auto;
    padding-bottom: 1px;
  }
  .tech-table tbody tr {
    height: 28px;
  }
  .tech-table td {
    height: 28px;
    line-height: 28px;
  }
  .filename-cell {
    height: 28px;
    line-height: 28px;
  }
  .filename-text {
    line-height: 28px;
  }
  .select-col {
    height: 28px;
    line-height: 28px;
  }
  .tech-radio {
    width: 14px;
    height: 14px;
    vertical-align: middle;
    margin: 0;
  }
  .tech-table {
    border-radius: 4px;
  }
}
</style>

